<template>
	<!-- 语音建议 -->
	<view class="content">
		<!-- 内容盒子 -->
		<view class="form">
			<!-- 语音列表 begin -->
			<view class="content-item list">
				<view class="row">
					<view class="grid" v-for="(item, index) in audioList" :key="index">
						<view class="recorder-advise"
							:style="{ width: `${getVoiceWidth(durationFormat(item.duration))}%` }"
							@tap="onPlayAudio(item.tempFilePath, index)">
							<!-- background: linear-gradient(to right, red, blue); /* 设置初始背景为红到蓝的线性渐变 */
            animation: gradientAnimation 3s infinite alternate; /* 应用名称为gradientAnimation的动画，持续时间为3秒，无限次重复并交替反向运行 */ -->
							<view class="bg">~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~</view>
							<view class="duration">
								{{ convertMilliseconds(item.countdown) }}
							</view>
							<view class="audio-play-animation">
								<view class="wifi-symbol">
									<view class="wifi-circle first"></view>
									<view
										:class="currentPlayAudioIndex === index ? ['wifi-circle', 'second', 'play-animation-1'] : ['wifi-circle', 'second']">
									</view>
									<view
										:class="currentPlayAudioIndex === index ? ['wifi-circle', 'third', 'play-animation-2'] : ['wifi-circle', 'third']">
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="grid">
						<view class="text-advise">
							语音内容语音内容，语音内容语音内容语音内容，语音内容语音内容，语音内容语，音内容语音内容语音内容语音内容语音内容语音。
						</view>
					</view>
					<view class="grid">
						<view class="text-advise">
							语音内容语音内容，语音内容语音
						</view>
					</view>
				</view>
			</view>
			<!-- 语音列表 end -->
			<!--
                    @submit：通知父组件，发送消息内容。
                    audioXY：手指在屏幕中的位置信息。
                    audioShow：是否弹出子组件
                    audioTouchendShow：是否结束录制
                    closeAudioShow：子组件通知父组件，结束录制，
                -->
			<chatAudio @submit="submit" :audioXY="audioXY" :audioShow="audioShow" :audioTouchendShow="audioTouchendShow"
				@closeAudioShow="audioTouchendShow = false, audioShow = false">
			</chatAudio>
			<!-- form-submit begin -->
			<view class="footer">
				<button type="button" @longpress="audioLongpress" @touchmove.stop.prevent="audioTouchmove"
					@touchend.stop.prevent="audioTouchendShow = true">
					<view v-if="audioShow"><uni-icons type="mic" color="#FFF" size="24"></uni-icons>正在说话...</view>
					<view v-else>按住说话</view>
				</button>
			</view>
			<!-- form-submit end -->
		</view>
	</view>
</template>

<script>
	import chatAudio from '@/components/recorder/chatAudio.vue';

	const innerAudioContext = uni.createInnerAudioContext();
	let interval = null;
	const defaultAudioList = [{
			tempFilePath: "http://tmp/0aMlw1RmF5it2663903297ea8134a5e17e2484f0c20a.durationTime=5475.aac",
			duration: 4000,
			countdown: 4000,
			fileSize: 29804
		},
		{
			tempFilePath: "https://m804.music.126.net/20240308155710/89c3086197c084399b36267ba2eb111a/jdymusic/obj/wo3DlMOGwrbDjj7DisKw/28482289852/f7d0/2cbc/1e7d/2c4dbad0b7d80ca7cfe29454930be206.mp3?_authSecret=0000018e1cfa03fc12300aaba0798997",
			duration: 317000,
			countdown: 317000,
			fileSize: 129804
		},
		{
			tempFilePath: "https://cg-sycdn.kuwo.cn/5778cae04aee2d2859ebfe8dce4b0d93/65eebc6f/resource/n2/39/68/2585512899.mp3",
			duration: 223000,
			countdown: 223000,
			fileSize: 129804
		},
		{
			tempFilePath: "https://m804.music.126.net/20240312160729/439d730b760121e80bfb932206ff05e5/jdymusic/obj/wo3DlMOGwrbDjj7DisKw/28482018850/0260/4652/5072/60ea64998275757b3e6c5aaaae2ac221.mp3?_authSecret=0000018e319ce3db05470aaba31417ae",
			duration: 233000,
			countdown: 233000,
			fileSize: 129804
		},
	]

	export default {
		components: {
			chatAudio, //语音组件
		},
		data() {
			return {
				// isRecording: false, //是否正在录音
				audioList: defaultAudioList, // 音频列表
				currentPlayAudioIndex: -1,
				audioShow: false, // 录制音频弹窗
				audioTouchendShow: false, // 是否结束录制音频
				audioXY: {
					x: 0,
					y: 0
				},
			}
		},
		onLoad() {
			innerAudioContext.onPlay(res => {
				console.log('onPlay', res);
			});
			innerAudioContext.onEnded(() => {
				this.currentPlayAudioIndex = -1;
			});
			innerAudioContext.onStop(() => {
				this.currentPlayAudioIndex = -1;
			});
		},
		onHide() {
			console.log('onHide');
			this.clearIntervalAudioIndex(this.currentPlayAudioIndex);
			innerAudioContext.stop();
		},
		onLastPageBackPress() {
			console.log('onLastPageBackPress');
		},
		watch: {
			audioList(val, oldVal) {
				console.log('audioList', val, oldVal);
			}
		},
		mounted() {},
		methods: {
			audioLongpress(e) {
				console.log('audioLongpress')
				this.clearIntervalAudioIndex(this.currentPlayAudioIndex);
				innerAudioContext.stop();

				this.audioShow = true;
			},
			// 录音长按
			audioTouchmove(e) {
				this.audioShow = true;
				this.audioTouchendShow = false;
				let x = e.changedTouches[0].clientX;
				let y = e.changedTouches[0].clientY;
				this.audioXY = {
					x: x,
					y: y
				};
			},
			// 发送
			submit(file, type) {
				console.log('submit', file, type);
				const obj = {
					...file,
					countdown: file.duration
				};
				this.audioList.push(obj);
			},
			durationFormat(val) {
				return (val / 1000).toFixed(0);
			},
			onPlayAudio(src, index) {
				if (this.currentPlayAudioIndex >= 0) {
					this.clearIntervalAudioIndex(this.currentPlayAudioIndex);
					innerAudioContext.stop();

					if (this.currentPlayAudioIndex !== index) {
						this.onOlay(src, index);
					}
				} else {
					this.onOlay(src, index);
				}
			},
			onOlay(src, index) {
				innerAudioContext.src = src;
				innerAudioContext.play();
				this.currentPlayAudioIndex = index;
				this.setIntervalAudioIndex(index);
			},
			setIntervalAudioIndex(index) {
				interval = setInterval(() => {
					if (this.audioList[index].countdown <= 0) {
						// 清除倒计时
						this.clearIntervalAudioIndex(index);
					} else {
						this.audioList[index].countdown = this.audioList[index].countdown - 1000;
					}
				}, 1000);
			},
			clearIntervalAudioIndex(index) {
				if (interval) clearInterval(interval);
				if (index >= 0) {
					this.audioList[index].countdown = this.audioList[index].duration;
				}
				console.log("倒计时结束");
			},
			convertMilliseconds(millis) {
				const totalSeconds = Math.floor(millis / 1000);
				const hours = Math.floor(totalSeconds / 3600).toString().padStart(2, "0");
				const minutes = Math.floor((totalSeconds % 3600) / 60).toString().padStart(2, "0");
				const seconds = (totalSeconds % 60).toString().padStart(2, "0");

				// return `${hours}时${minutes}分${seconds}秒`;
				return `${minutes}:${seconds}`;
			},
			/**
			 * 处理语音长度
			 * @param {Number} duration 
			 */
			getVoiceWidth(duration) {
				// 最小宽度 百分比
				const minPercentage = 30;
				// 最小值对应最小百分比
				const minVal = 10;
				// 最大宽度 百分比
				const maxPercentage = 100;
				// 最大值对应最大百分比
				const maxVal = 60;
				// 返回结果
				let result = "";
				// // 每秒钟的宽度
				// const widthPerSecond = 1;

				if (duration <= 10) {
					// result = minPercentage;
					return minPercentage;
				} else if (duration >= 60) {
					// result = maxPercentage;
					return maxPercentage;
				} else {
					// result = (((maxPercentage - minPercentage) / (maxVal - minVal)) * (duration - minVal) + minPercentage).toFixed(2);
					return (((maxPercentage - minPercentage) / (maxVal - minVal)) * (duration - minVal) + minPercentage)
						.toFixed(2);
				}
				return `${result}%`;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		padding: 20rpx;
	}

	.form {
		width: 100%;
		padding: 30rpx;
		background-color: $bg-color-white;
		border-radius: $border-radius-lg;

		.list {

			.row {
				display: flex;
				flex-wrap: wrap;

				.grid {
					width: 100%;
					display: flex;
					flex-direction: column;
					align-items: flex-end;
					margin: 10rpx 0;

					.recorder-advise {
						display: flex;
						justify-content: flex-end;
						align-items: center;
						background: #ad2325;
						color: #FFF;
						border-radius: 50rpx;
						border: 1rpx solid #c7c7c7;
						padding: 10rpx 20rpx;

						.bg {
							width: 100%;
							overflow: hidden;
						}

						.duration {
							margin-left: 10rpx;
						}

						// 语音播放动画
						.audio-play-animation {
							margin-right: 10rpx;

							.wifi-symbol {
								width: 50rpx;
								height: 50rpx;
								box-sizing: border-box;
								overflow: hidden;
								transform: rotate(315deg);

								.wifi-circle {
									border: 5rpx solid #FFF;
									border-radius: 50%;
									position: absolute;
								}

								.first {
									width: 10rpx;
									height: 10rpx;
									background: #cccccc;
									top: 45rpx;
									left: 45rpx;
								}

								.second {
									width: 25rpx;
									height: 25rpx;
									top: 35rpx;
									left: 35rpx;
									// animation: fadeInOut 1s infinite 0.2s;
								}

								.third {
									width: 40rpx;
									height: 40rpx;
									top: 25rpx;
									left: 25rpx;
									// animation: fadeInOut 1s infinite 0.4s;
								}

								.play-animation-1 {
									animation: fadeInOut 1s infinite 0.2s;
								}

								.play-animation-2 {
									animation: fadeInOut 1s infinite 0.4s;
								}
							}

							@keyframes fadeInOut {
								0% {
									opacity: 0;
									/*初始状态 透明度为0*/
								}

								100% {
									opacity: 1;
									/*结尾状态 透明度为1*/
								}
							}
						}
					}

					.text-advise {
						width: 100%;
						color: #707070;
						border: 1rpx solid #c7c7c7;
						padding: 15rpx;
					}
				}
			}
		}
	}

	.footer {
		height: 120rpx;
		padding: 10rpx 20rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: #FFFFFF;
		z-index: 999;
		box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);

		button {
			width: 100%;
			height: 80%;
			display: flex;
			justify-content: center;
			align-items: center;
			border-radius: 50rpx;
			color: #FFFFFF !important;
			background: #ad2325 !important;

			view {
				display: flex;
				align-items: center;
			}
		}
	}
</style>